define(function(require, exports, module) {
	'use strict';

    var rk = require('rk');
    require('../../su/xsySuRefer/widget');
var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil');


    var haveInit = false;

    $.widget('rk.xsyScheduleRefer', $.rk.xsySuRefer, {
        options: {
            iconClass: 'xsy_su_refer_schedule_icon'
        },
        _create: function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me._super();
            me.reload();
        },

        _init : function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;
        },

        reload : function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me._loadData({}, function(result){
                var config = {
                    className : 'xsy_schedule_refer',
                    iconClass: opt.iconClass,
                    linkOfMore : '/schedule.action?fromBelongId=' + me._getCommonData().belongId + '&fromDataId=' + me._getDetailId() + '&name=' + encodeURIComponent(me._getCommonData().name),
                    buttons: ['create'],
                    children: [
                        {
                            type: 'card',
                        }
                    ],
                    showEntityMenu : false
                };

                var self = result.self;
                var common = result.common;
                var maxRowNum = opt.attributes && opt.attributes.maxCardRowCount ? opt.attributes.maxCardRowCount : 6;
                opt.entityDataLength = self.dataCount ? self.dataCount : 0;
                opt.entityData = me._processData(self.entityData, maxRowNum);
                if(haveInit){
                    //me.bindData(result.self);
                   // me._initCardView();
                   me._render(config, result);
                    me._processEvent();
                }else{
                    me._render(config, result);
                    me.changeHeader(result.self);
                    me._processEvent();
                    haveInit = true;
                }
            });
        },

        _processData : function(data, maxCardRowCount){
            if(!data){
                return;
            }
            var sortData = data.sort(opSort);
            sortData.forEach(function(item){
                if(item.scheduleOrTask == 'schedule'){
                    if(item.isAllDay){
                        item.startDate = rk.formatText(item.startDate, 7, 'YYYY-MM-DD');
                        item.endDate = rk.formatText(item.endDate, 7, 'YYYY-MM-DD');
                    }else{
                        item.startDate = rk.formatText(item.startDate, 7, 'YYYY-MM-DD HH:mm');
                        item.endDate = rk.formatText(item.endDate, 7, 'YYYY-MM-DD HH:mm');
                    }
                    
                }else if(item.scheduleOrTask == 'task'){
                    item.planFinishDate = rk.formatText(item.planFinishDate, 7, 'YYYY-MM-DD HH:mm');
                }
            })
            return sortData.slice(0, maxCardRowCount);
            function opSort(a, b) {
                return (b.planFinishDate || b.startDate) - (a.planFinishDate || a.startDate) ;
            }
        },

        _initCardView : function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var entityData = opt.entityData;
            if(entityData && entityData.length > 0){

                var card = me._getCard();
                var tpl = rk.templateText(require("platform/widgets/crm/schedule/xsyScheduleRefer/card_task_item.tpl"), {entityData: entityData})
                card.html(tpl);

                me._triggerInnerEvent('onReferWidthData',{
                    dataCount : opt.entityDataLength
                });

            }else{
                me._triggerInnerEvent('onReferWidthoutData',{
                    dataCount : 0
                });
                var card = me._getCard();
                card.html('');
                card.hide();
            }

        },

        _processEvent : function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me._listenInnerEvent('onReferCreateClick', function(info){
                addScheduleOrTask();
            });

            elem.on('click', 'a.xsy_schedule_refer_task', function(evt) {
                evt.preventDefault();
                var $el = $(this),
                    checked = $el.hasClass('xsy_schedule_refer_task_done');
                if ($el.hasClass('xsy_schedule_refer_task_disabled') || $el.hasClass('xsy_schedule_refer_task_checkdisabled')) {
                    return;
                }
                $.post('/json/crm_task/change-status.action', {
                    taskId: $el.attr('entryid'),
                    taskStatus: checked ? 1 : 2
                }, null, 'json').done(function(json) {
                    if (json.status == 0) {
                        if (checked) {
                            $el.removeClass('xsy_schedule_refer_task_done').addClass('xsy_schedule_refer_task_normal').attr('title', rk.i18n('TASK_CLICK_FINISHED'));
                            $.msg(rk.i18n('TASK_RESTART_SUCCESS'),1);
                        } else {
                            $el.removeClass('xsy_schedule_refer_task_normal').addClass('xsy_schedule_refer_task_done').attr('title', rk.i18n('TASK_CLICK_CANCEL_FINISHED'));
                            $.msg(rk.i18n('TASK_HAVE_FINISHED'),1);
                        }
                    } else {
                        $.msg(rk.i18n('TASK_CHANGE_STATUS_ERROR'));
                    }
                }).fail(function(def, code, message) {
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                });
            });

            function addScheduleOrTask(){
                var start = moment(new Date().getTime() - 0);
                start.set('minutes', 0);
                start.set('second', 0);
                start.add(60, 'minutes');
                var end = moment(+start.toDate() + 30 * 60 * 1000)
                var config = {
                    startDate: start.format('YYYY-MM-DD'),
                    startTime: start.format('HH:mm:ss'),
                    endDate: end.format('YYYY-MM-DD'),
                    endTime: end.format('HH:mm:ss'),
                    isAllDay: false,
                    act: 'create',
                    ownerUser: SESSION.user,
                    entityId : opt.parentEntityId,
                    sourceEntity : {
                        id : me._getDetailId(),
                        name : me._getCommonData().name
                    },
                    success:function(json){
                        //TODO  这里立即刷新可能刷不出来新添加的数据，因为索引的新建不是实时的
                        //添加任务日程的接口添加当前添加的数据信息，然后通过js构造一条数据插入到卡片中
                        setTimeout(function(){me.reload()}, 2000);
                        
                        me._triggerOuterEvent('referDataUpdated');
                    }
                };
                scheduleUtil.popupEditor(config);
            }
        }
    });
});